package com.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import com.pojo.User;

import java.util.*;

@Component("myUserServiceImpl")
public class MyUserServiceImpl implements UserDetailsService {
    static Map<String,User> map = new HashMap<String, User>();
    static {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode = bc.encode("123");//对密码加密
        System.out.println(encode);
        encode = bc.encode("123");//对密码加密
        System.out.println(encode);
        User user = new User();
        user.setUsername("zs");
        user.setPassword(encode);
        User user1 = new User();
        user1.setUsername("ls");
        user1.setPassword(encode);
        map.put("user1",user);
        map.put("user2",user1);
    }
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        List<GrantedAuthority> list=new ArrayList<>();
        SimpleGrantedAuthority role1 = new SimpleGrantedAuthority("ROLE_ADD");
        list.add(role1);
        List<GrantedAuthority> list1=new ArrayList<>();
        SimpleGrantedAuthority role2 = new SimpleGrantedAuthority("ROLE_FIND");
        SimpleGrantedAuthority role3 = new SimpleGrantedAuthority("QUERY");
        list1.add(role2);
        list1.add(role3);
        Set<String> strings = map.keySet();
        for (String string : strings) {
            User user = map.get(string);
            if(name.equals(user.getUsername())){
                if("zs".equals(name)){
                    return new org.springframework.security.core.userdetails.User(name,user.getPassword(),list);
                }
                if("ls".equals(user.getUsername())){
                    return new org.springframework.security.core.userdetails.User(name,user.getPassword(),list1);
                }
            }
        }
        return null;
    }
}
